//express_demo.js 文件
var express = require("express");
var bodyParser = require("body-parser");
var multer = require("multer");
const cors = require("cors");
const fs = require("fs");

var app = express();
// 使用cors中间件，并传入一个选项对象
app.use(
  cors({
    origin: "http://localhost:3000", // 指定允许的来源
  })
);

// 使用cors中间件
app.use(cors());

app.use(express.static("public"));

app.use(bodyParser.urlencoded({ extended: false }));

//自定义中间件
function preUploadFile(req, res, next) {
  //dest 值为文件存储的路径;single方法,表示上传单个文件,参数为表单数据对应的key
  let upload = multer({
    dest: "public/temp/",
    limits: 1024 * 1024 * 10,
  }).single("file");
  upload(req, res, (err) => {
    //打印结果看下面的截图
    if (err) {
      res.send("err:" + err);
    } else {
      //将文件信息赋值到req.body中，继续执行下一步
      next();
    }
  });
}

// 暂存图片到public、temp目录
app.post("/uploadImgs", preUploadFile, function (req, res) {
  const response = {
    originalname: req.file.originalname,
    uuid: req.file.filename,
    status: "done",
  };
  res.end(JSON.stringify(response));
});

// 保存图片到public目录
app.post("/saveImgs", function (req, res) {
  console.log("req.body", req.body);
  const uuids = req.body.uuids;
  // for (uuid of uuids) {
  //   const oldPath = `public/temp/${uuid}`;
  //   const newPath = `public/imgs/${uuid}.png`;
  //   // 通过流的方式将oldPath流文件移动到newPath，并添加文件类型后缀.png
  //   const readStream = fs.createReadStream(oldPath);
  //   const writeStream = fs.createWriteStream(newPath);
  //   // 将旧文件移动到新文件
  //   readStream.on("data", (chunk) => {
  //     writeStream.write(chunk);
  //   });

  //   readStream.on("end", () => {
  //     writeStream.end();
  //   });

  //   readStream.on("error", (err) => {
  //     console.error("移动文件时发生错误:", err);
  //   });
  // }
  // res.end("success");
});

app.get("/getImgs", function (req, res) {
  // 返回public目录下所有文件名
  const files = fs.readdirSync("public/imgs/");
  const fileNames = files.map((file) => {
    return {
      name: file,
    };
  });
  res.end(JSON.stringify(fileNames));
});

var server = app.listen(3001, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log("应用实例，访问地址为 http://%s:%s", host, port);
});
